<html>
<head><title>Nicofarre test</title></head>
<body style="margin: 0; cursor: none">
<script src="../tma.js"></script>
<script src="mv_common.js"></script>
<script>
Line = function () {
  this._init = false;
  var p = function () { return (Math.random() - 0.5) * 10000; };
  var v = function () { return (Math.random() - 0.5) * 200; };
  var cv = function () { return Math.random() * Math.random() * 0.01; };
  this._p1 = [];
  this._p2 = [];
  this._v1 = [];
  this._v2 = [];
  this._c = [];
  this._cv = [];
  this._n = 32;
  this._size = 10000;
  for (var i = 0; i < this._n; ++i) {
    this._c[i] = [Math.random(), Math.random(), Math.random(), 1.0];
    this._cv[i] = [cv(), cv(), cv(), 1.0];
    this._p1[i] = [p(), p(), p()];
    this._p2[i] = [p(), p(), p()];
    this._v1[i] = [v(), v(), v()];
    this._v2[i] = [v(), v(), v()];
  }
};

Line.prototype.update = function (p, v, max, min) {
  p[0] += v[0];
  p[1] += v[1];
  p[2] += v[2];
  if (p[0] < min || max < p[0]) v[0] = -v[0];
  if (p[1] < min || max < p[1]) v[1] = -v[1];
  if (p[2] < min || max < p[2]) v[2] = -v[2];
};

Line.prototype.draw = function (api) {
  api.setAlphaMode(true, api.gl.DST_COLOR, api.gl.ZERO);
  var rate = 0.91;
  if (!this._init) {
    this._init = true;
    api.clear(api.gl.COLOR_BUFFER_BIT | api.gl.DEPTH_BUFFER_BIT);
  }
  api.fill([rate, rate, rate, 1.0]);
  api.setAlphaMode(true, api.gl.ONE, api.gl.ONE);
  for (var i = 0; i < this._n; ++i) {
    api.color = this._c[i];
    api.drawLine([this._p1[i][0], this._p1[i][1], this._p1[i][2]],
                 [this._p2[i][0], this._p2[i][1], this._p2[i][2]]);
    this.update(this._p1[i], this._v1[i], this._size, -this._size);
    this.update(this._p2[i], this._v2[i], this._size, -this._size);
    this.update(this._c[i], this._cv[i], 1.0, 0);
  }
}

var line = new Line();

tma.extlibs = [ 'ext/gl-matrix.js', 'ext/mv/MajVj.js' ];
tma.onload = function () {
  var r = 1;
  var width = 1920 / r;
  var height = 1080 / r;
  var vj = new MajVj(width, height, true);
  MajVj.loadAllPlugins().then(_(function () {
    var wall = vj.create('frame', 'nicofarre3d',
                         { draw: line.draw.bind(line) });
    var fx = vj.create('effect', 'nicofarre', { front: false,
                                                position: [0, 0, 0]});
    fx.setController(controller);
    var fbo = vj.screen().createFrameBuffer(width, height);
    vj.screen().setAlphaMode(false);
    vj.run(_(function (delta) {
      if (emulate)
        fbo.bind();
      vj.screen().fillColor(0.0, 0.0, 0.0, 1.0);
      wall.draw(delta);
      if (emulate) {
        vj.screen().bind();
        vj.screen().fillColor(0.0, 0.0, 0.0, 1.0);
        fx.draw(delta, fbo.texture);
      }
      vj.screen().flush();
    }));
    window.onresize = function () {
      vj.onresize();
      fx.onresize(vj.aspect());
    };
  }), function (e) { console.log('plugin load error: ' + e); });
};
</script>
</body>
</html>
